/*
 * @Author: wangjun haodreams@163.com
 * @Date: 2024-05-10 09:02:21
 * @LastEditors: wangjun haodreams@163.com
 * @LastEditTime: 2024-12-16 16:35:24
 * @FilePath: \libs\tail\tail.go
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
package tailsnap

import (
	"bufio"
	"os"
	"strings"
	"unicode"

	"gitee.com/haodreams/libs/fixedlist"
)

func TailFile(path string, num int, orders ...bool) (lines []*string, err error) {
	f, err := os.Open(path)
	if err != nil {
		return
	}
	defer f.Close()
	buf := bufio.NewReader(f)
	queue := fixedlist.NewFixList[string](num)
	for line, err := buf.ReadString('\n'); err == nil || len(line) > 0; line, err = buf.ReadString('\n') {
		newLine := strings.TrimRightFunc(line, unicode.IsSpace)
		if newLine == "" {
			continue
		}
		queue.Push(&newLine)
	}
	orderAsc := true
	subOrderAsc := true
	switch len(orders) {
	case 1:
		orderAsc = orders[0]
	case 2:
		orderAsc = orders[0]
		subOrderAsc = orders[1]
	}
	if orderAsc {
		lines = queue.Stack(0, queue.Len(), subOrderAsc)
	} else {
		lines = queue.Queue(0, queue.Len())
	}
	return
}
